/**
 *  弹出框页面穿透问题
 */
var ModalHelper = (function (bodyCls) {
    var scrollTop;
    return {
        afterOpen: function () { //记录弹框弹出时滚动条高度，弹框弹出调用
            scrollTop = document.scrollingElement.scrollTop;
            document.body.classList.add(bodyCls);
            document.body.style.top = -scrollTop + 'px';
        },
        beforeClose: function () { // 弹框关闭时还原滚动条高度 关闭时调用此方法
            document.body.classList.remove(bodyCls);
            // scrollTop lost after set position:fixed, restore it back.
            document.scrollingElement.scrollTop = scrollTop;
        }
    };
})('modal-open');

/*
 ** @fn 要执行的函数
 ** @delay 间隔时长
 ** @immediate 是否立即触发一次
 */
function debounce(fn, delay, immediate) {
    if (typeof fn !== 'function') {
        throw new TypeError('need a function arguments')
    }
    var timer = null // 定时器，用来 setTimeout
    return function () {
        // 保存函数调用时的上下文和参数，传递给 fn
        var context = this
        var args = arguments
        // 每次这个返回的函数被调用，就清除定时器，以保证不执行 fn
        clearTimeout(timer)
        if (immediate) {
            var callNow = !timer
            timer = setTimeout(function () {
                timer = null
            }, delay)
            if (callNow) fn.apply(context, args)
        } else {
            // 当返回的函数被最后一次调用后（也就是用户停止了某个连续的操作），
            // 再过 delay 毫秒就执行 fn
            timer = setTimeout(function () {
                fn && fn.apply(context, args)
            }, delay)
        }

    }
}

function throttle(fn, delay) {
    if (typeof fn !== 'function') {
        throw new TypeError('need a function arguments')
    }
    var timer = null // 定时器，用来 setTimeout
    var startTime = Date.now()
    return function () {
        var curTime = Date.now()
        var remaining = delay - (curTime - startTime)
        var context = this
        var args = arguments
        // console.log('remaining:'+remaining)
        clearTimeout(timer);
        if (remaining <= 0) {
            fn.apply(context, args);
            startTime = Date.now();
        } else {
            timer = setTimeout(fn, remaining);
        }
    }
}

// 字符截取工具函数
function getSubstring(str, end_index, is_ellipsis) {
    if (typeof str !== 'string') {
        throw new TypeError('need a string arguments')
    }
    let result = '';
    result = is_ellipsis ? (str.length > end_index ? str.substring(0, end_index) + '...' : str) : (str.length > end_index ? str.substring(0, end_index) : str)
    return result
}

// 获取浏览器地址栏参数工具函数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function FormatImg(html) {
    var newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        var match = match.replace(/style=\"(.*)\"/gi, 'class="img-responsive"');
        return match;
    });
    return newContent;
}

//是否是移动端
function IsMobile() {
    let userAgent = navigator.userAgent,
        Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    // console.log('userAgent:', userAgent)
    return Agents.some((i) => {
        return userAgent.includes(i)
    })
}

let isMobile = IsMobile() || $(window).width() <= 768

// 判断滚动态哦是否触底
// function scrollLoadMore(cb) {
//     var lowerThreshold = 50; // 距离底部多少距离触发
//     var viewH = $(document).height(), // 整个文档流高度
//         scrollHeight = $(window).scrollTop(), // 滚动条高度
//         screenHeight = $(window).height(); // 浏览器窗口高度
//     // console.log("整个文档流高度:" + viewH)
//     // console.log("浏览器窗口高度:" + screenHeight)
//     // console.log("滚动条高度:" + scrollHeight)
//     // console.log("滚动条高度:" + parseInt(scrollHeight + screenHeight))
//     if (viewH - (scrollHeight + screenHeight) < lowerThreshold) {
//         //console.log('触底加载');  
//         cb && cb()
//     }
// }

// 动态创建视频节点（video）
function createVideo() {
    var videoContainers = $('.video-bg')
    if (videoContainers.length > 0) {
        videoContainers.each(function () {
            let self = $(this)
            // let posterName = $(this).data("poster")
            // let poster = isMobile ? `${posterName}@2x.jpg` : `${posterName}.jpg`
            let sourceUrl = isMobile ? $(this).data("mobile-url") : $(this).data("pc-url")
            //console.log(poster)
            if(sourceUrl){
                self.html(`<video autoplay muted loop preload="auto" x-webkit-airplay='true' x5-video-player-type='h5'
                x5-video-player-fullscreen='true' playsinline class="video">
                <source src="${sourceUrl}">
            </video>`)
            }       
        })
    }
}

$(function () {

    createVideo() // 动态创建首屏幕banner视频背景

    // 自定义下拉菜单
    if ($('.J-select-item').length > 0) {
        let selectContainer = $('.J-select-item')
        let selectHandle = selectContainer.find('.select-text')
        selectHandle.click(function () {
            let self = $(this)
            if (!self.parent().hasClass('opened')) {
                self.parent().addClass("opened")
            } else {
                self.parent().removeClass("opened")
            }

        })

        selectContainer.find('.select-options li').click(function () {
            let self = $(this)
            self.addClass('selected').siblings().removeClass('selected')
            selectHandle.html(self.data("value"))
            self.parents('.J-select-item').removeClass("opened")
        })

        selectContainer.mouseleave(function () {
            $(this).removeClass("opened")
        });
    }

    const baseH = isMobile ? $(window).height() * 0.25 : $(window).height() * 0.5;
    var isTop = true;
    $(window).scroll(function () {
        let _scrollTop = $(window).scrollTop();
        //console.log(_scrollTop)
        if (_scrollTop > baseH) {
            if (isTop) {
                console.log("给顶部导航添加背景")
                $('.header').addClass('scrolling')
                isTop = false
            }
        } else {
            if (!isTop) {
                $('.header').removeClass('scrolling')
                isTop = true
            }
        }
    })

    // 移动端下拉菜单触发
    if (isMobile) {
        // 点击按钮弹出导航区块
        $('.m-nav-switch').click(function () {
            const headerContainer = $(this).parents('.header')
            if (headerContainer.hasClass('opened')) {
                headerContainer.removeClass('opened')
                ModalHelper.beforeClose()
            } else {
                headerContainer.addClass('opened')
                ModalHelper.afterOpen();
            }
        })

        $('.nav .drop-menu .m-drop-arrow').click(function () {
            let self = $(this).parent()
            if (self.hasClass('active')) {
                self.removeClass('active')
            } else {
                self.addClass('active').siblings().removeClass('active')
            }
        })

        // 微信内部视频自动播放
        const bgVideos = document.querySelectorAll('.video-bg .video');
        document.addEventListener("WeixinJSBridgeReady", function () {
            for (let i = 0; i < bgVideos.length; i++) {
                bgVideos[i].play()
            }
        }, false);

    }
    // 点阵背景动画
    const staggeringGrid1Groups = document.querySelectorAll('.staggering-grid-1')
    staggeringGrid1Groups.forEach((ele, i) => {
        const childEles = ele.getElementsByClassName('el')
        anime({
            targets: childEles,
            opacity: [{
                    value: 0,
                    easing: 'easeOutSine',
                    duration: 500
                },
                {
                    value: .6,
                    easing: 'easeInOutQuad',
                    duration: 300
                }
            ],
            scale: [{
                    value: .1,
                    easing: 'easeOutSine',
                    duration: 500
                },
                {
                    value: 1,
                    easing: 'easeInOutQuad',
                    duration: 300
                }
            ],
            loop: true,
            delay: anime.stagger(200, {
                grid: [10, 3],
                from: 'center'
            })
        });
    })

    const staggeringGrid2Groups = document.querySelectorAll('.staggering-grid-2')
    staggeringGrid2Groups.forEach((ele, i) => {
        //console.log(ele)
        const childEles = ele.getElementsByClassName('el')
        anime({
            targets: childEles,
            opacity: [{
                    value: 0,
                    easing: 'easeOutSine',
                    duration: 500
                },
                {
                    value: .6,
                    easing: 'easeInOutQuad',
                    duration: 600
                }
            ],
            scale: [{
                    value: .1,
                    easing: 'easeOutSine',
                    duration: 500
                },
                {
                    value: 1,
                    easing: 'easeInOutQuad',
                    duration: 600
                }
            ],
            loop: true,
            delay: anime.stagger(200, {
                grid: [6, 4],
                from: 'center'
            })
        });
    })


    //公司联系信息简单tab切换
    $('.contact-infor-tabbox').each(function () {
        let $this = $(this)
        let inforTabConts = $this.find('.infor-tab-cont')
        let inforTabNavItems = $this.find('.infor-tab-nav .item').click(function () {
            let idx = inforTabNavItems.index(this)
            let self = $(this)
            self.addClass('active').siblings().removeClass('active')
            inforTabConts.eq(idx).fadeIn().siblings('.infor-tab-cont').css("display", "none")
        })
    })

    // scrollTrigger 自定义 滚动添加active
    if ($('.J-scroll-group').length > 0) {
        const scrollAniGroup = gsap.utils.toArray('.J-scroll-group')
        scrollAniGroup.forEach((ele, i) => {
            ScrollTrigger.create({
                trigger: ele,
                start: "top 85%",
                toggleClass: 'active',
                end: "bottom 10%",
                //onToggle: self => console.log("toggled, isActive:", self.isActive),
                onUpdate: self => {
                    //console.log("progress:", self.progress.toFixed(3), "direction:", self.direction, "velocity", self.getVelocity());                 
                }
            });
        });
    } else {
        //console.log("没有调用gsap")
    }



})